<?php

namespace App\Http\Controllers\Wxpay;

use Illuminate\Http\Request;

ini_set('date.timezone','Asia/Shanghai');

require_once "WxPayData.php";
require_once "WxPayApi.php";
require_once "WxPayNativePay.php";
require_once "phpqrcode.php";

use WxPayUnifiedOrder;
use NativePay;
use QRcode;
use WxPayResults;
use WxPayDataBase;
use App\Rad_users;
use App\Order;
use App\Coupon;
use App\Radcheck;
use App\Manage_user_list;
use App\Product;
use App\Radreply;
use App\Rad_manage;
use App\Recharge;
use App\Extension;

class WxPayNotifyController extends WxPayDataBase
{

    public function PayCallback()
    {
        //获取通知的数据
        $xml = file_get_contents('php://input');
        // 如果返回成功则验证签名
        try {
            $result = WxPayResults::Init($xml);

            self::fwrite($result);

            if($result['result_code'] == 'SUCCESS' && $result['return_code']=='SUCCESS')
            {
                switch ($result['attach'])
                {
                    case 'pay' : return $this->WxPay($result);break;
                    case 'recharge' : return $this->WxRecharge($result);break;
                }

            }

        } catch (WxPayException $e){
            $msg = $e->errorMessage();

            $this->values['return_code'] = 'FAIL';
            $this->values['return_msg'] = '';
            return $this->ToXml();
        }

        $this->values['return_code'] = 'FAIL';
        $this->values['return_msg'] = '';
        return $this->ToXml();

   }

    /**
     * @param $result
     * @return string
     * @throws \WxPayException
     *微信充值
     */
    public function WxRecharge($result)
    {
        $order = Recharge::where('order_no',$result['out_trade_no'])->where('status',0)->first();

        $manage = Rad_manage::find($order->user_id);
        if($manage != NULL)
        {

            $manage->balance = $manage->balance + $order->recharge_money;
            $order->status = 1;
            $order->save();
            $manage->save();

            $this->values['return_code'] = 'SUCCESS';
            $this->values['return_msg'] = 'OK';
            return $this->ToXml();

        }else{
            $this->values['return_code'] = 'FAIL';
            $this->values['return_msg'] = '';
            return $this->ToXml();
        }

    }
   
   
   
    /**
     * @param $result
     * @return string
     * @throws \WxPayException
     * 微信购买回调
     */
    public function WxPay($result)
   {
       $order = Order::where('order_no',$result['out_trade_no'])->first();
       $order->status = 1;
       $order->save();
       //  优惠号码标记已使用
       if($order->coupon_code)
       {
           $coupon =  Coupon::where('coupon_code',$order->coupon_code)->first();
           $coupon->is_use = 1;
           $coupon->save();
       }
       $time = time();   //   当前时间

       //修改会员状态
       $user = Rad_users::find($order->to_user);

       $surplus_time  =  strtotime($user->expired_at);//  当前套餐到期时间
       if ($surplus_time<$time){
           $surplus_time = $time;
           $user->vip = 0;
       }

       //会员类型   不相相同   如果是高级会员转普通会员 直接转换后续时间，如果是普通会员转高级会员，普通会员清零后新开高级会员
       if ($user->vip==1 && $order->vip==2){
           $surplus_time = $time;
       }
       $user->vip = $order->vip;


       switch($order->product_id)
       {
           case 1: $time = 30*86400*$order->month+$surplus_time;break;
           case 2: $time = 90*86400*$order->month+$surplus_time;break;
           case 3: $time = 360*86400*$order->month+$surplus_time;break;
           case 4: $time = 7*86400*$order->month+$surplus_time;break;
           case 11:$time = 180*86400*$order->month+$surplus_time;break;                 //半年基础

           case 6: $time = 30*86400*$order->month+$surplus_time;break;     // 月度套餐高级
           case 7: $time = 90*86400*$order->month+$surplus_time;break;     // 一季度高级
           case 8: $time = 360*86400*$order->month+$surplus_time;break;    // 一年高级
           case 9: $time = 180*86400*$order->month+$surplus_time;break;         //半年高级
       }


       $date = date('Y-m-d H:i:s',$time);
       $user->expired_at = $date;

       //  radius  数据同步
       $time = date("d M Y H:i:s ",$time);
       Radcheck::where('username',$user->username)->where('attribute','=','Expiration')->update(['value'=>$time]);



       $order = Order::where('order_no',$result['out_trade_no'])->first();
       $product = Product::find($order->product_id);
       $speed = '';

       $set_meal_type = '';

       switch($product->type_id)
       {
           case 1:$speed = '2048k/2048k';$set_meal_type = 2;break;
           case 2:$speed = '4096k/4096k';$set_meal_type = 3;break;
       }

       if($product->activity_flag == 1)
       {
           $product->number = $product->number - 1;
           $product ->save();
       }

       $user->set_meal_type = $set_meal_type;
       $user->account_type = '付费';

       $radreply = Radreply::where('username',$user->username)->where('attribute','Mikrotik-Rate-Limit')->first();
       $radreply->value = $speed;
       $radreply->save();

       $user->save();

        //  推广购买记录
       try{
           $extension = Extension::where('order_no',$result['out_trade_no'])->first();
           $extension->status = 1;
           $extension->save();

       }catch (\Exception $exception){
       }



       $this->values['return_code'] = 'SUCCESS';
       $this->values['return_msg'] = 'OK';
       return $this->ToXml();
   }




    static function fwrite($data){

        $file=storage_path('logs/wxpay.log');
        $myFile = fopen($file, "a+") or die("Unable to open file!");
        $data = json_encode($data);
        $txt = $data."\n";
        fwrite($myFile, $txt);
        fclose($myFile);
    }

}
